//首先导入express
var express = require("express")

//1.创建web应用
var app = express()

//2.创建静态资源服务器     app.use() 注册中间件,    express.static 是托管静态资源的中间件
app.use( express.static('jingtaitai') );

//在post接口设置前，处理post请求参数的中间键
app.use(express.json())
app.use(express.urlencoded({extended:false}))


    //定义返回给客户端的数据
    var ccc = [
        { email:'122222222@qq.com',name:'张伟啊',phone:'13611129070',pass:'1234',ingroup:'编辑组',isadmin:true,zhuangtai:'正常' },
        { email:'144444444@qq.com',name:'李煜啊',phone:'13611129071',pass:'1234',ingroup:'编辑组',isadmin:true,zhuangtai:'异常' },
        { email:'144444444@qq.com',name:'李煜啊',phone:'13611129072',pass:'1234',ingroup:'编辑组',isadmin:true,zhuangtai:'正常' },
        { email:'144444444@qq.com',name:'李煜啊',phone:'13611129073',pass:'1234',ingroup:'编辑组',isadmin:false,zhuangtai:'异常' },
        { email:'144444444@qq.com',name:'李煜啊',phone:'13611129074',pass:'1234',ingroup:'编辑组',isadmin:true,zhuangtai:'正常' },
        { email:'144444444@qq.com',name:'李煜啊',phone:'13611129075',pass:'1234',ingroup:'编辑组',isadmin:true,zhuangtai:'异常' },
        { email:'144444444@qq.com',name:'李煜啊',phone:'13611129076',pass:'1234',ingroup:'编辑组',isadmin:true,zhuangtai:'正常' },
        { email:'144444444@qq.com',name:'李煜啊',phone:'13611129077',pass:'1234',ingroup:'编辑组',isadmin:true,zhuangtai:'正常' },
        { email:'144444444@qq.com',name:'李煜啊',phone:'13611129078',pass:'1234',ingroup:'编辑组',isadmin:false,zhuangtai:'异常' },
        { email:'144444444@qq.com',name:'李煜啊',phone:'13611129079',pass:'1234',ingroup:'编辑组',isadmin:true,zhuangtai:'正常' },
        { email:'144444444@qq.com',name:'李煜啊',phone:'13611129011',pass:'1234',ingroup:'编辑组',isadmin:false,zhuangtai:'正常' }
    ]
//3.创建api接口服务器
//箭头函数是请求处理器
app.get( '/user/list',(req,res)=>{
    var {page,count}=req.query

    //分页
    var newccc = ccc.slice( (page-1)*count, page*count );
    res.send({msg:'请求成功！',list:newccc})
} )
app.post( '/user/login',(req,res)=>{
    //拆分是另外一种写法
    var {phone,pass}=req.body
    console.log('收到了来自客户端的请求');
    res.send({ code:200,msg:'登录成功！'})
} )
//模糊搜索接口
app.get( '/user/search', (req,res)=>{
    //接收参数
    var { searchkey } = req.query;
    //根据参数,从用户的name属性中filter过滤
    var newccc = ccc.filter((item)=>{
        return  new RegExp(searchkey).test( item.name ) 
    })
    //返回数据
    res.send({ code:200,msg:'查询成功!',list:newccc })
})


//登陆相关服务器接口
app.post( '/user/denglu', (req,res)=>{
    
    //想要接收post类型请求的参数 必须提前设置能解析post请求参数的中间件 express.json 和 express.urlencoded 
    var {phone,pass} = req.body;

    //用来自客户端的数据 做判断, 判断是否在服务端的用户列表中
    var i = ccc.findIndex((item,index)=>{
        return item.phone == phone && item.pass == pass;
    })

    //如果i不是-1, 说明来自客户端的数据是合法的.
    if( i != -1 ){
        //登陆成功时, 可以一并返回 登陆成功的用户信息,登陆令牌
        res.send( {code:200, msg:'登陆成功!',userinfo: ccc[i], token:'' } );
    }else{
        res.send( {code:400, msg:'登陆失败!'} );
    }
} )
//4.设置监听端口
app.listen(8080,()=>{
    console.log('服务器正在运行');
});